﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.CMS.Content;
using MethodWorx.CMS.Plugins;
using MethodWorx.CMS.Services;

namespace MethodWorx.CMS.Workflow.PublishContentItem
{
    public class PublishContentItemWorkflowComponent : WorkflowComponent<PublishContentItemConfigurationController>
    {
        public PublishContentItemWorkflowComponent(Plugin plugin)
            : base(plugin)
        {
        }

        public static Guid ComponentId = Guid.Parse("{68BE2251-ACA6-4B30-B979-85FE9E56AE4A}");

        public override Guid Id
        {
            get { return ComponentId;  }
        }

        public override string Category
        {
            get { return "Content";  }
        }

        public override string Name
        {
            get { return "Publish Content Item";  }
        }

        public override string Description
        {
            get { return "Published the choosen content item";  }
        }

        public override string View
        {
            get { return "PublishContentItemConfigurationView.ascx"; }
        }

        public override StepExecutionResult Execute(IWorkflowExecutionContext context, IWorkflowConfiguration configuration)
        {
            //
            //  ok, here we go..
            var currentPage = context.GetWorkflowValue("currentPage") as Page;
            var config = configuration as PublishContentItemConfiguration;

            if (currentPage != null && config != null)
            {
                //  ok find the item in the context first
                var contentItem = context.GetWorkflowValue(config.ContentItem.TrimStart('{').TrimEnd('}')) as ContentItem;
                //  then look in the current page
                if (contentItem == null)
                    contentItem = currentPage.ChildContent.FirstOrDefault(c => c.Name.ToLower() == this.ParseString(config.ContentItem, context.GetAllWorkflowValues()).ToLower());

                if (contentItem == null)
                    return StepExecutionResult.Error("Content Item Not Found");

                //
                //  else, lets publish
                ContentService service = new ContentService(context.CmsDataProvider);
                service.PublishContentItem(contentItem);

                return StepExecutionResult.Ok();
            }
            else
                return StepExecutionResult.Error("Unexpected error, invalid configuration");
        }
    }
}
